package com.vhly.remoteapi;

import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

/**
 * Created by IntelliJ IDEA.
 * User: vhly[FR]
 * Date: 2010-12-5
 * Time: 12:45:51
 * Email: vhly@163.com
 */
public abstract class APIClient {

    protected Token requestToken;

    protected Token accessToken;

    protected Verifier verifier;

    /**
     * Get OAuth Service for Remote API
     *
     * @return OAuthService
     */
    public abstract OAuthService getOAuthService();

    public abstract boolean loadToken();

    public abstract boolean saveToken();

    public String invoke(OAuthRequest req) {
        String ret = null;
        if (req != null) {
            OAuthService oauth = getOAuthService();
            boolean bok = true;
            if (!isAuthorization()) {
                bok = loadToken();
            }
            if (bok) {
                oauth.signRequest(accessToken, req);
                Response response = req.send();
                ret = response.getBody();
            }
        }
        return ret;
    }

    public boolean isAuthorization() {
        return accessToken != null;
    }

    public boolean needRequestToken() {
        return accessToken == null && requestToken == null;
    }

    public void setVerifierCode(String code) {
        verifier = null;
        verifier = new Verifier(code);
    }
}
